package com.xiaocz.hblsubstitutedriving.activities.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.track.AMapTrackClient;
import com.amap.api.track.query.entity.DenoiseMode;
import com.amap.api.track.query.entity.DriveMode;
import com.amap.api.track.query.entity.HistoryTrack;
import com.amap.api.track.query.entity.MapMatchMode;
import com.amap.api.track.query.entity.Point;
import com.amap.api.track.query.entity.RecoupMode;
import com.amap.api.track.query.entity.ThresholdMode;
import com.amap.api.track.query.entity.Track;
import com.amap.api.track.query.model.HistoryTrackRequest;
import com.amap.api.track.query.model.HistoryTrackResponse;
import com.amap.api.track.query.model.QueryTerminalRequest;
import com.amap.api.track.query.model.QueryTerminalResponse;
import com.amap.api.track.query.model.QueryTrackRequest;
import com.amap.api.track.query.model.QueryTrackResponse;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xiaocz.common.Common;
import com.xiaocz.common.http.AsyncHttpPostFormData;
import com.xiaocz.common.http.AsyncHttpResponse;
import com.xiaocz.common.http.AsyncOkHttpClient;
import com.xiaocz.common.http.AsyncResponseHandler;
import com.xiaocz.common.model.RspModel;
import com.xiaocz.common.utils.AccountManagers;
import com.xiaocz.common.utils.SPUtil;
import com.xiaocz.common.widgets.dialog.CustomDialog;
import com.xiaocz.common.widgets.load.LoadFactory;
import com.xiaocz.common.widgets.load.core.LoadManager;
import com.xiaocz.common.widgets.load.view.AbsView;
import com.xiaocz.hblsubstitutedriving.App;
import com.xiaocz.hblsubstitutedriving.R;
import com.xiaocz.hblsubstitutedriving.base.BaseActivity;
import com.xiaocz.hblsubstitutedriving.model.OrderInfo;
import com.xiaocz.hblsubstitutedriving.utils.Constants;
import com.xiaocz.hblsubstitutedriving.utils.SimpleOnTrackListener;
import com.xiaocz.hblsubstitutedriving.widget.EmptyView;
import com.xiaocz.hblsubstitutedriving.widget.ErrorView;
import com.xiaocz.hblsubstitutedriving.widget.LoadingView;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 订单明细
 */
public class OrderDetailsActivity extends BaseActivity {

    @BindView(R.id.layout_base)
    RelativeLayout layoutBase;
    @BindView(R.id.layout_wait)
    LinearLayout layoutWait;
    @BindView(R.id.tv_wait)
    TextView tvWait;
    @BindView(R.id.layout_zc)
    LinearLayout layoutZc;
    @BindView(R.id.tmv_track)
    TextureMapView textureMapView;
    @BindView(R.id.btn_test)
    Button btnTest;

    /**
     * DATA
     */
    private LoadManager mLoadManager;
    private String orderNo;
    private AMapTrackClient aMapTrackClient;
    private OrderInfo orderInfo;
    private List<Polyline> polyLines = new LinkedList<>();
    private List<Marker> endMarkers = new LinkedList<>();

    public static void show(Context context, String orderNo) {
        Intent intent = new Intent(context, OrderDetailsActivity.class);
        intent.putExtra("ORDER_NO", orderNo);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_order_details;
    }

    @Override
    protected boolean initArgs(Bundle bundle) {
        if (bundle != null) {
            orderNo = bundle.getString("ORDER_NO");
        }
        return !TextUtils.isEmpty(orderNo);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        textureMapView.onCreate(savedInstanceState);
        super.init(savedInstanceState);
    }

    @Override
    protected void initWidgets() {
        super.initWidgets();
        mLoadManager = LoadFactory.getInstance().register(layoutBase, new AbsView.OnReloadListener() {
            @Override
            public void onReload(View view) {
                mLoadManager.showStateView(LoadingView.class);
                webOrderInfo();
            }
        });
        aMapTrackClient = new AMapTrackClient(getApplicationContext());// 不要使用Activity作为Context传入
        btnTest.setVisibility(View.GONE);//测试按钮
    }

    @OnClick({R.id.tv_regulation, R.id.tv_kf, R.id.btn_test})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_regulation://计费规则
                ExpenseStandardActivity.show(mContext);
                break;
            case R.id.tv_kf://扣费详情
                StringBuilder builder = new StringBuilder();
                if (orderInfo.getInsurancemoney().doubleValue() > 0) {
                    builder.append(String.format("保险费%s元\n", orderInfo.getInsurancemoney()));
                }
                if (orderInfo.getRoyaltymoney().doubleValue() > 0) {
                    builder.append(String.format("信息费%s元\n", orderInfo.getRoyaltymoney()));
                }
                if (orderInfo.getReward_money().doubleValue() > 0) {
                    builder.append(String.format("司机推荐分成%s元", orderInfo.getReward_money()));
                }
                dialogKF(builder.toString());
                break;
            case R.id.btn_test:
                clearTracksOnMap();
//                history();
                queryTrack();
                break;
        }
    }

    private void dialogKF(String message) {
        final CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
        View layout = LayoutInflater.from(mContext).inflate(R.layout.dialog_base, null);
        builder.setContentView(layout);
        builder.setGravity(Gravity.CENTER);
        builder.setDialogWidthAndPX(WindowManager.LayoutParams.MATCH_PARENT);
        builder.setDialogHeightAndPX(WindowManager.LayoutParams.WRAP_CONTENT);
        final CustomDialog dialog = builder.create();
        TextView tvTitle = layout.findViewById(R.id.tv_title);
        TextView tv_view = layout.findViewById(R.id.tv_message);
        tvTitle.setText("费用组成");
        tv_view.setText(message);
        layout.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }


    int pageSize = 1;

    private void queryTrack() {
        SimpleDateFormat dateFormat = new SimpleDateFormat(Common.DateType.dateIF, Locale.CHINA);
        long startTime = System.currentTimeMillis();
        try {
            startTime = dateFormat.parse(orderInfo.getStarttime()).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        // 搜索最近12小时以内上报的属于某个轨迹的轨迹点信息，散点上报不会包含在该查询结果中
        QueryTrackRequest queryTrackRequest = new QueryTrackRequest(
                Constants.SERVICE_ID,
                Long.parseLong(String.valueOf(SPUtil.get("TERMINAL_ID", 0L))),
                orderInfo.getTraceId(),// 轨迹id，传-1表示查询所有轨迹
                startTime,
                startTime + 24 * 60 * 60 * 1000
                , DenoiseMode.NON_DENOSE,// 去噪
                MapMatchMode.NON_MAPMATCH,// 绑路
                ThresholdMode.GPS_WIFI_THRESHOLD,// 不进行精度过滤
                DriveMode.DRIVING,// 当前仅支持驾车模式
                RecoupMode.DRIVING,// 距离补偿
                50,// 距离补偿，只有超过5km的点才启用距离补偿
                1,  // 结果应该包含轨迹点信息
                pageSize,  // 返回第1页数据，由于未指定轨迹，分页将失效
                999// 每页条数
        );
        aMapTrackClient.queryTerminalTrack(queryTrackRequest, new SimpleOnTrackListener() {

            @Override
            public void onQueryTrackCallback(QueryTrackResponse queryTrackResponse) {
                if (queryTrackResponse.isSuccess()) {
                    try {
                        List<Track> tracks = queryTrackResponse.getTracks();
                        // 查询成功，tracks包含所有轨迹及相关轨迹点信息
                        for (int i = 0; i < tracks.size(); i++) {
                            System.out.println("--------" + tracks.get(i).getDistance() + ":" + tracks.get(i).getPoints().size());
                        }
                        List<Point> pointList = tracks.get(0).getPoints();
                        for (Point p : pointList) {
                            LatLng latLngs = new LatLng(p.getLat(), p.getLng());
                            latLng.add(latLngs);
                        }
                        if (pointList.size() == 999) {
                            pageSize++;
                            queryTrack();
                        } else {
                            drawTrackOnMap(latLng);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    // 查询失败
                    App.getInstance().showMessage("查询失败");
                }
            }
        });
    }

    List<LatLng> latLng = new ArrayList<>();

    /**
     * 历史
     */
    private void history() {
        aMapTrackClient.queryTerminal(new QueryTerminalRequest(Constants.SERVICE_ID, Constants.TERMINAL_NAME), new SimpleOnTrackListener() {
            @Override
            public void onQueryTerminalCallback(QueryTerminalResponse queryTerminalResponse) {
                if (queryTerminalResponse.isSuccess()) {
                    if (queryTerminalResponse.isTerminalExist()) {
                        long tid = queryTerminalResponse.getTid();
                        // 搜索最近12小时以内上报的轨迹
                        HistoryTrackRequest historyTrackRequest = new HistoryTrackRequest(
                                Constants.SERVICE_ID,
                                tid,
                                System.currentTimeMillis() - 12 * 60 * 60 * 1000,
                                System.currentTimeMillis(),
                                0,
                                0,
                                5000,   // 距离补偿，只有超过5km的点才启用距离补偿
                                0,  // 由旧到新排序
                                1,  // 返回第1页数据
                                100,    // 一页不超过100条
                                ""  // 暂未实现，该参数无意义，请留空
                        );
                        aMapTrackClient.queryHistoryTrack(historyTrackRequest, new SimpleOnTrackListener() {
                            @Override
                            public void onHistoryTrackCallback(HistoryTrackResponse historyTrackResponse) {
                                if (historyTrackResponse.isSuccess()) {
                                    HistoryTrack historyTrack = historyTrackResponse.getHistoryTrack();
                                    if (historyTrack == null || historyTrack.getCount() == 0) {
                                        Toast.makeText(mContext, "未获取到轨迹点", Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                    List<Point> points = historyTrack.getPoints();
                                    List<LatLng> latLng = new ArrayList<>();
                                    for (Point p : points) {
                                        LatLng latLngs = new LatLng(p.getLat(), p.getLng());
                                        latLng.add(latLngs);
                                    }
                                    drawTrackOnMap(latLng);
                                } else {
                                    Toast.makeText(mContext, "查询历史轨迹点失败，" + historyTrackResponse.getErrorMsg(), Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    } else {
                        Toast.makeText(mContext, "Terminal不存在", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    @Override
    protected void initData() {
        webOrderInfo();
        super.initData();
    }

    /**
     * 订单详情
     */
    private void webOrderInfo() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("driver_id", AccountManagers.getUserId());
        asyncHttpPostFormData.addFormData("orderNo", orderNo);
        okHttpClient.post(Common.Constant.API_IP + "api/Order/getOrderDetail", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                mLoadManager.showStateView(ErrorView.class);
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<OrderInfo>>() {
                }.getType();
                RspModel<OrderInfo> rspModel = getAnalysisBase(mLoadManager, response, type, "订单详情");
                if (rspModel == null) {
                    mLoadManager.showStateView(EmptyView.class);
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                            orderInfo = rspModel.getData();
                            if ("1".equals(orderInfo.getIswaittimeout())) {//1超时等待
                                layoutWait.setVisibility(View.VISIBLE);
                                layoutZc.setVisibility(View.GONE);
                                tvWait.setText(String.valueOf("等待" + orderInfo.getWaittime() + "分钟\n等待费" + orderInfo.getWaitmoney() + "元"));
                            } else {//0未超时等待
                                layoutWait.setVisibility(View.GONE);
                                layoutZc.setVisibility(View.VISIBLE);
                                valueShow(rspModel.getData());
                                Type typeTrack = new TypeToken<List<LatLng>>() {
                                }.getType();
                                List<LatLng> trackList = new Gson().fromJson(rspModel.getData().getLocusdata(), typeTrack);
                                if (trackList != null && "[]".equals(trackList.toString())) {
                                    trackList.add(new LatLng(Double.parseDouble(orderInfo.getChufalat()), Double.parseDouble(orderInfo.getChufalong())));
                                    trackList.add(new LatLng(Double.parseDouble(orderInfo.getMudilat()), Double.parseDouble(orderInfo.getMudilong())));
                                }
                                drawTrackOnMap(trackList);
                            }
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        mLoadManager.showStateView(ErrorView.class);
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    private void clearTracksOnMap() {
        for (Polyline polyline : polyLines) {
            polyline.remove();
        }
        for (Marker marker : endMarkers) {
            marker.remove();
        }
        endMarkers.clear();
        polyLines.clear();
    }

    /**
     * 轨迹绘制
     */
    private void drawTrackOnMap(List<LatLng> latLngs) {
        if (latLngs != null && !"[]".equals(latLngs.toString())) {
            LatLngBounds.Builder boundsBuilder = new LatLngBounds.Builder();
            PolylineOptions polylineOptions = new PolylineOptions();
            polylineOptions.color(Color.BLUE).width(20);
            if (latLngs.size() > 0) {
                // 起点
                MarkerOptions markerOptions = new MarkerOptions()
                        .position(latLngs.get(0))
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
                endMarkers.add(textureMapView.getMap().addMarker(markerOptions));
            }
            if (latLngs.size() > 1) {
                // 终点
                MarkerOptions markerOptions = new MarkerOptions()
                        .position(latLngs.get(latLngs.size() - 1))
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
                endMarkers.add(textureMapView.getMap().addMarker(markerOptions));
            }
            for (LatLng latLng : latLngs) {
                polylineOptions.add(latLng);
                boundsBuilder.include(latLng);
            }
            Polyline polyline = textureMapView.getMap().addPolyline(polylineOptions);
            polyLines.add(polyline);
            textureMapView.getMap().animateCamera(CameraUpdateFactory.newLatLngBounds(boundsBuilder.build(), 80));
        }
    }

    @BindView(R.id.tv_start_money)
    TextView tvStartMoney;
    @BindView(R.id.tv_beyond_money)
    TextView tvBeyondMoney;
    @BindView(R.id.tv_await)
    TextView tvAwait;
    @BindView(R.id.tv_discount_coupon)
    TextView tvDiscountCoupon;
    @BindView(R.id.tv_extra_charges_name)
    TextView tvExtraChargesName;
    @BindView(R.id.tv_extra_charges)
    TextView tvExtraCharges;
    @BindView(R.id.tv_all_in_cost)
    TextView tvAllInCost;
    @BindView(R.id.tr_view)
    TableRow tableRow;
    @BindView(R.id.tv_subsidy_name)
    TextView tvSubsidyName;
    @BindView(R.id.tv_subsidy_price)
    TextView tvSubsidyPrice;
    @BindView(R.id.tv_ss)
    TextView tvSs;
    @BindView(R.id.tv_kf)
    TextView tvKf;

    /**
     * 数据显示
     *
     * @param info 订单信息
     */
    private void valueShow(OrderInfo info) {
        orderInfo = info;
        tvStartMoney.setText(String.format("%s公里%s元",info.getQibukm(),info.getQibumoney()));
        tvBeyondMoney.setText(String.format("%s公里%s元",info.getChaochukm(),info.getChaochumoney()));
        tvAwait.setText(String.format("%s分钟%s元",info.getWaittime(),info.getWaitmoney()));
        tvDiscountCoupon.setText(String.format("-%s元",info.getDiscountmoney()));
        tvExtraChargesName.setText("".equals(info.getOthermoneytxt()) ? "额外费用" : info.getOthermoneytxt());
        tvExtraCharges.setText(String.format("%s元",info.getOthermoney()));
        tvAllInCost.setText(String.format("总费用：%s元",info.getMoney()));
        if (info.getTempname() != null && !"".equals(info.getTempname())) {
            tableRow.setVisibility(View.VISIBLE);
            tvSubsidyName.setText(info.getTempname());
            tvSubsidyPrice.setText(String.format("%s元",info.getTempprice()));
        }
        if (info.getShishoumoney() != null) {
            tvSs.setText(String.format("%s元", info.getShishoumoney()));
        } else {
            tvSs.setText("0元");
        }
        tvKf.setText(String.format("%s元>", info.getInsurancemoney().add(info.getRoyaltymoney()).add(info.getReward_money())));
    }
}
